package com.jltx.compiler;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author aidenquan
 * Created by junlintianxia on 2020/08/26.
 */
public class MyServiceCenter {
    private static ConcurrentHashMap<String, IService> mCenter = new ConcurrentHashMap<>();

    public static void registerMyService(Class<? extends IService> serviceClazz, Class<? extends IService> serviceImplClazz) {
        String keyName = serviceClazz.getName();
        registerMyService(keyName, serviceImplClazz);
    }

    public static void registerMyService(String keyName, Class<? extends IService> serviceImplClazz) {
        IService iService = mCenter.get(keyName);
        if (iService == null) {
            try {
                iService = serviceImplClazz.newInstance();
                mCenter.put(keyName, iService);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public static <T> T getMyService(Class<? extends IService> serviceClazz) {
        String keyName = serviceClazz.getName();
        return getMyService(keyName);
    }
    public static <T> T getMyService(String keyName) {
        IService iService = mCenter.get(keyName);
        return iService != null ? (T) iService : null;
    }

    public static void unRegisterMyService(Class<? extends IService> serviceClazz) {
        String keyName = serviceClazz.getName();
        unRegisterMyService(keyName);
    }

    public static void unRegisterMyService(String keyName) {
        mCenter.remove(keyName);
    }
}
